#ifndef OBJECTFACTORY_H
#define OBJECTFACTORY_H

#include <QObject>
#include <QHash>

class ObjectFactory
{
public:
    template<typename T>
    static void registerClass()
    {
        // 最后一个参数是函数指针，只有才调用时才需要传入参数
        const char * pClassname = T::staticMetaObject.className();
        constructors().insert(T::staticMetaObject.className(), &constructorHelper<T>);
    }

    static QObject* createObject(const QByteArray& className, QObject* parent = NULL)
    {
        Constructor constructor = constructors().value(className);
        if (constructor == NULL)
            return NULL;
        return (*constructor)(parent); // constructor其实是 registerClass()函数中传入的函数指针
    }

private:
    typedef QObject* (*Constructor)(QObject* parent);

    template<typename T>
    static QObject* constructorHelper(QObject* parent )
    {
        return new T(parent);
    }

    static QHash<QByteArray, Constructor>& constructors()
    {
        static QHash<QByteArray, Constructor> instance;
        return instance;
    }
};

#endif // OBJECTFACTORY_H
